import store from '@/store'
import tinymce from 'tinymce/tinymce'
import { v4 as uuid } from 'uuid'
import { pinyin } from 'pinyin-pro'
import addPage from '@/utils/commands/addPage'
import { sleep } from '@/utils/helpers'
/**
 * 编辑器的索引修改
 * @param {*} editor
 */
export default function (editor) {
  editor.on('updateIndex', async () => {
    function updateIndexPage(editor, nodes, pageType = 'index') {
      const reg = () => /[\u200B-\u200D\uFEFF"‘’“”【】《》]/g //使用函数避免 lastIndex
      const doc = tinymce.activeEditor.getDoc()
      // 2. 索引
      // 2.1 先移除原先的索引
      const selector = `#tinymce>.page-wrapper [data-page-type="${pageType}"] p[data-block-id^="block"],
                        #tinymce>.page-wrapper [data-page-type="${pageType}"] p[data-block-id^="blkid"]`
      editor.dom.remove(editor.dom.select(selector))
      // 2.2 更新新的索引
      const paras = [...doc.querySelectorAll(`#tinymce>.page-wrapper [data-page-type="${pageType}"] .page-body p`)]
      const lastPara = paras.length ? paras[paras.length - 1] : null
      const obj = {}
      nodes.forEach((item) => {
        const content = item.content.replace(reg(), '').trim()
        if (/^(?![a-zA-Z\u4e00-\u9fa5]).*/g.test(content)) {
          if (!obj['其他']) {
            obj['其他'] = []
          }
          obj['其他'].push(item)
          return
        }
        const str = pinyin(item.content, { toneType: 'none' }).replace(reg(), '').trim()
        const letter = str[0].toUpperCase()
        if (obj[letter]) {
          obj[letter].push(item)
        } else {
          obj[letter] = [
            {
              content: letter,
              id: uuid(),
              type: 'letter'
            },
            item
          ]
        }
      })
      if (obj['其他']?.length) {
        const f = (x) => {
          const code = x.content
            .replace(/[\u200B-\u200D\uFEFF]/g, '')
            .trim()
            .charCodeAt(0)

          return code > 47 && code < 58 ? code + 100000 : code // 数字放最后
        }

        obj['其他'] = obj['其他'].sort((a, b) => f(a) - f(b))
        obj['其他'].unshift({
          content: '其他',
          id: uuid(),
          type: 'letter'
        })
      }
      const f1 = (x) => x.replace(reg(), '').trim().charCodeAt(0)
      const letters = Object.keys(obj).sort((a, b) => f1(a) - f1(b))
      const sorted = letters.reduce((prev, letter) => [...prev, ...obj[letter]], [])
      const html = sorted.reduce((acc, i) => {
        const blockId = i.id?.replace(/[a-z0-9]{8}/, pageType === 'index' ? 'blkidxzh' : 'blkidxen')
        const dataId = i.id?.replace(/[a-z0-9]{8}/, pageType === 'index' ? 'bizidxzh' : 'bizidxen')
        if (i.type === 'letter') {
          return (
            acc +
            `<p contenteditable="false"
                            class="letter-row"
                            data-type="paragraph"
                            data-lang="en"
                            data-id="${dataId}"
                            data-block-id="${blockId}"
                            >${i.content}</p>`
          )
        }
        return (
          acc +
          `<p contenteditable="false"
                          class="row link-row"
                          data-link-type="bizIndex"
                          data-type="paragraph"
                          data-id="${dataId}"
                          data-referred-id="${i.id}"
                          data-block-id="${blockId}"
                          data-content="${i.content}"
                          data-content-number="${i.contentNumber}"
                          >
                            <span>${i.content}</span>
                            <span class="dot-line"></span>
                            <span>${i.contentNumber}</span>
                          </p>`
        )
      }, '')
      const newParas = editor.dom.createFragment(html)
      lastPara && editor.dom.insertAfter(newParas, lastPara)
    }

    const [zh = [], en = []] = store.getters.indexNodes

    // 1. 中文索引
    await sleep()
    if (editor.dom.select(`#tinymce>.page-wrapper [data-page-type="index"]`)?.length === 0) {
      addPage(52)
      await sleep()
    }

    updateIndexPage(editor, zh, 'index')

    // 2. 英文索引
    await sleep()
    if (editor.dom.select(`#tinymce>.page-wrapper [data-page-type="indexEn"]`)?.length === 0) {
      addPage(53)
      await sleep()
    }

    updateIndexPage(editor, en, 'indexEn')
  })
}
